package com.service.product;

import com.domain.HttpResponse;
import com.domain.ex.BizException;
import com.domain.ex.Codes;
import com.domain.myenum.ProductUnitEnum;
import com.domain.myenum.RoleEnum;
import com.dto.IncomeDto;
import com.dto.ProductDto;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mapper.generator.ShProductMapper;
import com.mapper.self.ProductMapper;
import com.mapper.self.ProductTypeMapper;
import com.pojo.ShProduct;
import com.pojo.ShProductType;
import com.pojo.ShShop;
import com.service.shop.ShopService;
import com.utils.RandomUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/2/18 0018.
 */
@Service
public class ProductServiceImpl implements ProductService {

  @Autowired
  private ShProductMapper shProductMapper;
  @Autowired
  private ProductMapper productMapper;
  @Autowired
  private ShopService shopService;
  @Autowired
  private ProductTypeMapper productTypeMapper;


  @Override
  public Object save(ShProduct shProduct) {
    ensureProductLegal(shProduct);
    ShShop shop = shopService.queryByEmail(shProduct.getCompanyEmail());
    if (StringUtils.isBlank(shop.getEmail())) {
      throw BizException.create(Codes.ParamError, "请先创建门店");
    }
    if (productMapper.countProductByShopEmail(shop.getEmail()) >= 10) {
      throw BizException.create(Codes.ParamError, "至多只能上架10件商品");
    }
    // - 商品名称重复校验
    ShProduct shProduct1 = productMapper.queryByNameAndShopId(shProduct.getName(), shop.getId());
    if (shProduct1 != null) {
      throw BizException.create(Codes.ParamError, "商品名称重复");
    }
    shProduct.setCreatetime(new Date());
    // - 设置Bigdecimal的精度
    shProduct.getPrice().setScale(2);
    shProduct.getInventory().setScale(2);
    shProduct.setShopId(shop.getId());
    shProduct.setUuid(RandomUtils.getUuid());
    shProductMapper.insertSelective(shProduct);
    return HttpResponse.OK();
  }

  private void ensureProductLegal(ShProduct shProduct) {
    // - 空校验
    if (shProduct.getPrice() == null) {
      throw BizException.create(Codes.ParamError, "输入单价");
    }
    if (shProduct.getInventory() == null) {
      throw BizException.create(Codes.ParamError, "输入库存");
    }
    if (shProduct.getOriginalPrice().compareTo(shProduct.getPrice()) > 0) {
      throw BizException.create(Codes.ParamError, "商品成本价格不得高于售价");
    }
  }

  @Override
  public Object list(int page, int limit, Integer deleted, String email,Integer soldOut) {
    List<ProductDto> productDtoList = Lists.newArrayList();
    if (page > 0) {
      page = page - 1;
    }
    if ("null".equals(email)) {
      email = null;
    }
    email = null;
    List<ShProduct> shProducts = null;
    shProducts = productMapper.list(page * limit, limit, deleted, email,soldOut);
    if (CollectionUtils.isEmpty(shProducts)) {
      return productDtoList;
    }
    List<ShProductType> list = productTypeMapper.list(null, 1000, 0);
    Map<Integer, ShProductType> productTypeMap = buildProductTypeMap(list);
    parseProductUnit(shProducts);
    Map<String, List> productMap = buildClassifyProductMap(shProducts);
    ShProductType productType = null;
    for (String productTypeId : productMap.keySet()) {
      productType = productTypeMap.get(Integer.valueOf(productTypeId));
      ProductDto productDto = new ProductDto();
      if (productType == null) {
        productDto.setType("其他分类");
        productDto.setRemark("其他分类");
      } else {
        productDto.setType(productType.getName());
        productDto.setRemark(productType.getRemark());
      }
      productDto.setList(productMap.get(productTypeId));
      productDtoList.add(productDto);
    }
    return productDtoList;
  }

  private Map<String, List> buildClassifyProductMap(List<ShProduct> shProducts) {
    Map<String, List> productMap = Maps.newHashMap();
    for (ShProduct shProduct : shProducts) {
      if (!productMap.containsKey(shProduct.getProductType())) {
        productMap.put(shProduct.getProductType(), Lists.newArrayList());
      }
      productMap.get(shProduct.getProductType()).add(shProduct);
    }
    return productMap;
  }

  private void parseProductUnit(List<ShProduct> shProducts) {
    for (ShProduct shProduct : shProducts) {
      // - 解析产品单位
      shProduct.setUnit(ProductUnitEnum.queryStatusVal(Integer.valueOf(shProduct.getUnit())));
    }
  }

  private Map<Integer, ShProductType> buildProductTypeMap(List<ShProductType> list) {
    Map<Integer, ShProductType> productTypeMap = Maps.newHashMap();
    for (ShProductType productType : list) {
      productTypeMap.put(productType.getId(), productType);
    }
    return productTypeMap;
  }

  @Override
  public Object update(ShProduct shProduct) {
    ShProduct shProduct1 = shProductMapper.selectByPrimaryKey(shProduct.getId());
    if (shProduct1 == null) {
      return HttpResponse.create(Codes.ParamError, "没有查询到数据");
    }
    shProduct.setCompanyEmail(shProduct1.getCompanyEmail());
    shProduct.setDeleted(0);
    shProduct.setCreatetime(shProduct1.getCreatetime());
    shProduct.setSales(shProduct1.getSales());
    productMapper.update(shProduct);

    return HttpResponse.OK();
  }

  @Override
  public Object batchDel(Integer[] productIds) {
    int ret = productMapper.batchDel(productIds);
    return HttpResponse.OK();
  }

  @Override
  public Object updateProductImg(Integer productId, String url) {
    productMapper.updateProductImg(productId, url);
    return HttpResponse.OK();
  }

  @Override
  public Object updateProductStatus(Integer productId, Integer deleted) {
    if (productId == null || deleted == null) {
      return HttpResponse.create(Codes.SystemDeclare, "上/下架商品数据校验失败");
    }
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    Object obj = request.getSession().getAttribute("roleId");
    if (obj == null) {
      return HttpResponse.create(Codes.SystemDeclare, "权限不足");
    }
    Integer roleId = Integer.valueOf(obj.toString());
    if (roleId != RoleEnum.Shop.getCode()) {
      return HttpResponse.create(Codes.SystemDeclare, "权限不足");
    }
    productMapper.updateProductStatus(productId, deleted);
    return HttpResponse.OK();
  }

  @Override
  public IncomeDto calIncome(Integer productId) {
    ShProduct product = shProductMapper.selectByPrimaryKey(productId);
    IncomeDto incomeDto = new IncomeDto();
    if (product == null) {
      incomeDto.setPart1(BigDecimal.ZERO);
      incomeDto.setPart2(BigDecimal.ZERO);
    }
    BigDecimal price = product.getPrice();
    BigDecimal originalPrice = product.getOriginalPrice();
    // - 派息
    BigDecimal part1 = price.subtract(originalPrice).multiply(BigDecimal.valueOf(0.1)).multiply(BigDecimal.valueOf(0.8)).setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal part2 = price.subtract(originalPrice).multiply(BigDecimal.valueOf(0.1)).multiply(BigDecimal.valueOf(0.2)).setScale(2, BigDecimal.ROUND_HALF_UP);
    incomeDto.setPart1(part1);
    incomeDto.setPart2(part2);
    return incomeDto;
  }
}
